//
//  TJPictureView.swift
//  TJSinaWeibo
//
//  Created by 唐后能 on 16/4/14.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SDWebImage

// 定义最大列数.
let maxColum = 3

// 两侧间距.
let margin:CGFloat = 8

// 计算cell的宽高.
var picWH = (UIScreen.mainScreen().bounds.width - 2*margin - (CGFloat(maxColum)-1) * margin) / CGFloat(maxColum)

class TJPictureView: UICollectionView {

    let Identifier:String = "Identifier"
    var picURLS:[NSURL]? {
    
        didSet {
        
            // 1,根据图片数量,更新collectinView的宽高约束.
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(caculatorCollectionViewSize())
            }
            
            // 2,刷新数据.
            reloadData()
        }
    }
    // 定义流水布局.
    private var flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        backgroundColor = UIColor.clearColor()
        // 设置让tableView成为自己的数据源.
        self.dataSource = self
        self.delegate = self
        // 注册cell>
        self.registerClass(TJPictureViewCell.self, forCellWithReuseIdentifier: Identifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 根据图片数量,计算collectionView的尺寸.
    private func caculatorCollectionViewSize()->CGSize {
    
        flowLayout.itemSize = CGSizeMake(picWH,picWH )
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        
        let count = picURLS?.count ?? 0
        
        // 1),没有图片.
        if count == 0 {
        
            return CGSizeZero
        }
        
        // 2),有1张图片.
        if count == 1 {
        
            // 返回图片本身大小.
//            let size = CGSize(width: 180, height: 90)
            // 先设置默认大小.
            var size = CGSize(width: picWH, height: picWH)
            // 从沙盒中获取缓存图片.
            let url = picURLS![0]
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url.absoluteString) {
                // 如果能从磁盘中获取图片.
                size = image.size   // SDWeb在3.7.3之后,会将实际图片根是@2或@3来除以2或3
//                TJPrint("\(size)")
                size = CGSize(width: size.width * UIScreen.mainScreen().scale, height: size.height * UIScreen.mainScreen().scale)
            } else {
                print("默认图片")
            }
            // 对图片的特殊尺寸进行处理.
            if size.width < 40 {
            
                size.width = 40
            }
            
            if size.width > UIScreen.mainScreen().bounds.width*0.5 {
            
                size.width = UIScreen.mainScreen().bounds.width*0.5
            }
            
            flowLayout.itemSize = size
            return size
        }
        
        // 3),有多张图片.
        flowLayout.minimumInteritemSpacing = margin
        flowLayout.minimumLineSpacing = margin
        var colum = maxColum //默认有三列
        if count == 2 || count == 4 {
            
            colum = 2
        }
        
        // 计算行数.
        // 行数 = (总个数 + 列数 - 1) / 列数
        let row = (count + colum - 1) / colum
        
        // 计算collectionVeiw的宽度.
        let width = CGFloat(colum) * picWH + (CGFloat(colum) - 1) * margin + 1 //加上1是为了防止精度丢失造成width和height不够.
        
        // 计算collectioniew的高度.
        let height = CGFloat(row) * picWH + (CGFloat(row) - 1) * margin + 1
        
        return CGSize(width: width, height: height)
    }
    
    
}

// MARK: - 数据源.
extension TJPictureView:UICollectionViewDataSource,UICollectionViewDelegate {

    // 数据源方法.
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picURLS?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Identifier, forIndexPath: indexPath) as? TJPictureViewCell
        cell?.imgURL = picURLS?[indexPath.item]
        return cell!
    }
    
    // 代理方法.
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

        let browser = SDPhotoBrowser()

        browser.sourceImagesContainerView = self

        browser.imageCount = picURLS?.count ?? 0

        browser.currentImageIndex = indexPath.item

        browser.delegate = self

        browser.show()
    }
}

//  MARK:SDPhotoBrowser代理方法.
extension TJPictureView:SDPhotoBrowserDelegate {

    // 返回临时占位图.(用cell的背景图)
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        // 获取cell.
        let cell = cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! TJPictureViewCell
        
        // 获取原来的小图
        let image = cell.imgView.image ?? UIImage(named: "avatar")
        
        return image
    }
    
    // 返回高亮状态图. 新浪返回的picURLS数组中的为"bmiddle"是压缩图   ... "thumbnail"为高清大图.
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
//         return picURLS![index]
        let URLString = picURLS?[index].absoluteString //把url转成string.
//        TJPrint("\(URLString)")
        let thumbnailString = URLString?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: thumbnailString ?? "")
    }
}

// MARK: - 新建collectionViewCell类,显示配图数据.
class TJPictureViewCell:UICollectionViewCell {

    var imgURL:NSURL? {
        
        didSet{
            imgView.sd_setImageWithURL(self.imgURL)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    
    private func setupUI(){
        
        // 1,添加子控件.
        contentView.addSubview(imgView)
        // 2,添加约束.
        imgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }

    // MARK: - 懒加背景载图片.
    private lazy var imgView:UIImageView = UIImageView()
    
}


